<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/23
 * Time: 17:42
 */

namespace Modules\Shop\service;

use Blade;
use Modules\Shop\Entities\Article;
use Modules\Shop\Entities\Category;

class TagService
{
    //创建自定义标签
    public function make(){
        //echo '创建自定义';
        //创建分类标签
        $this->category();
        //创建文章标签
        $this->article();
    }
//创建分类标签方法
    public function category(){
        //自定义模板文件
        //第一个参数是定义的标签的名字
        //第二个参数是回调函数，也就是自己定义模板标签会执行的动作由回调函数决定
        Blade::directive('category',function ($canshu){
           //判断调用标签的时候是否传递了参数
            $canshu = $canshu ?: '[]';
            //定义字符集字符串
            $php = <<<php
<?php
\$params = $canshu;
//获取所有分类数据
\$db = new \Modules\Shop\Entities\Category();
//如果存在自定义标签参数才加上一些条件
if(isset(\$params['pid'])){
    \$db = \$db->where('pid',\$params['pid']);
}
\$data = \$db->get();
foreach(\$data as \$v){
\$v['url'] = '/shop/lists/' . \$v['id'];
?>
php;
            return $php;

        });

        //定义分类标签结束
        Blade::directive('endcategory',function (){
            $php = <<<php
<?php
}
?>
php;
            return $php;

        });
    }

    //创建文章标签方法
    public function article(){
        //开始
        Blade::directive('article',function ($canshu){
            $canshu = $canshu ?: '[]';
            //定义定界符的字符串
            $php = <<<php
<?php

\$params = $canshu;

\$db = new \Modules\Shop\Entities\Article();

//如果存在cid值,就代表需要获取某个分类下的文章
if(isset(\$params['cid'])){
\$db = \$db->where('category_id',\$params['cid']);
}

//如果存在iscommend值,就取推荐文章
if(isset(\$params['iscommend'])){
\$db = \$db->where('iscommend',\$params['iscommend']);
}

//如果存在hot值,就按照点击数排序
if(isset(\$params['hot'])){
\$db = \$db->orderBy('click','desc');
}

//如果存在limit值,就截取传递的limit条数,如果不存在,就取默认的5条,为了模板布局
if(isset(\$params['limit'])){
\$db = \$db->limit(\$params['limit']);
}else{
\$db = \$db->limit(8);
}

\$article = \$db->get();

foreach(\$article as \$a){
//处理文章点击跳转地址
\$a['url'] = '/shop/detail/' . \$a['id'];
?>
php;
                return $php;
        });
        //结束
        Blade::directive('endarticle',function (){
            //定义定界符的字符串
            $php = <<<php
<?php
}
?>
php;
            return $php;
        });
    }

}